package fr.syntheses.blog.Model.DAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

import org.apache.log4j.Logger;

import fr.syntheses.blog.beans.Article;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.Transaction;


public class ArticleDAOH  extends ModeleDAO {

	private Logger log = Logger.getLogger(currentClassToLog);

	// Variables
	private List<Article> listeArticle;

	
    // retourner la liste des clients
	public List<Article> getListeArticle() {	
		// Variables
		listeArticle = new ArrayList<Article>();
		Session session = null;
		Query query = null;
		
		try {
		//HibernateUtil.createSessionFactory();
		
		session = HibernateUtil.getSession();
		
		try {
			query = session.createQuery("from Article order by datepublication desc");
			Iterator articles = query.iterate();
			
			while (articles.hasNext()) {
				listeArticle.add((Article) articles.next());
			}

		} finally {
//			if (session.isOpen()) {
//				session.close();
//			}
			
			//A voir ...
		}
		} catch (HibernateException e) {
			log.fatal("/* ATTENTION GRAVE ERREUR LORS DE LA CREATION DE LA SESSION FACTORY HB */");
			log.fatal(e);
		} finally {
			//HibernateUtil.closeSessionFactory();
		}
		return listeArticle;
	}

	public void create(Article article) {
		
		Session session = null;
		Transaction transaction = null;

		try {
		//	HibernateUtil.createSessionFactory();
		
			session = HibernateUtil.getSession();
		
			try {
				transaction = session.beginTransaction(); 
				session.save(article);
				session.flush();
				transaction.commit();
			} catch (Exception e) {
				if (transaction != null) {
					transaction.rollback();
					log.error(e);
				}
			} finally {
				//session.close();
			}
		} catch (HibernateException e) {
			log.fatal("/* ATTENTION GRAVE ERREUR LORS DE LA CREATION DE LA SESSION FACTORY HB */");
			log.fatal(e);
		} finally {
			//HibernateUtil.closeSessionFactory();
		}
	}


	
	public void read() {
	}

	public void update() {
	}

	public void delete() {
	}
	
}